//
//  ICMessageTableViewCell.m
//  ICome
//
//  Created by ENN on 16/3/7.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMessageTableViewCell.h"
#import "ICHeadImageView.h"
#import "ICGroup.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "ICMessageDatabase.h"
#import "ICGroupUser.h"
#import "NSMutableAttributedString+Extension.h"
#import "ICSearchMessage.h"
#import "UIImage+AvatarGeneration.h"
#import "ICSyncManager.h"

static const CGFloat leftPadding = 8;

#define imageViewHeight  (App_Frame_Width - 80)

@interface ICMessageTableViewCell ()

@property (nonatomic, weak) ICHeadImageView *avatarImageView;
@property (nonatomic, weak) UILabel *usernameLabel;
@property (nonatomic, weak) UILabel *dateLabel;
@property (nonatomic, weak) UILabel *messageLabel;
@property (nonatomic, strong)UILabel *alertMessageLabel;
@property (nonatomic, strong) UIButton *unreadButton;
@property (nonatomic, strong)UILabel *todoStatus;
@property (nonatomic, strong)UIImageView *busyImageView;
@end

@implementation ICMessageTableViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self avatarImageView];
        [self usernameLabel];
        [self dateLabel];
        [self messageLabel];
        [self unreadButton];
        [self busyImageView];
    }
    return self;
}

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"cell";
    ICMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[ICMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.layer.backgroundColor = TABLECELLSELECTCOLOR.CGColor;
    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.usernameLabel.font = [UIFont systemFontOfSize:17];
    cell.dateLabel.font = [UIFont systemFontOfSize:12];
    cell.messageLabel.font = [UIFont systemFontOfSize:14];
    cell.alertMessageLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}

- (void)setGroup:(ICGroup *)group
{
    _group   = group;
    
    if (group.isTop == 1) {
        int type = [group.gType intValue];
        if (type == ICGroup_NOTIFY ||
            type == ICGroup_TODO ||
            type == ICGroup_CHANCE ||
            type == ICGroup_ROBOT ||
            type == ICGroup_SERVICE ||
            type == ICGroup_DIRECTM) {
            self.backgroundColor = [UIColor whiteColor];
        } else {
            self.backgroundColor = BACKGROUNDCOLOR;
        }
    } else {
        self.backgroundColor = [UIColor whiteColor];
    }
    
    if (group.unReadCount > 0) {
        if (group.unReadCount > 99) {
            [self.unreadButton setTitle:@"99+" forState:UIControlStateNormal];
        } else {
            [self.unreadButton setTitle:[NSString stringWithFormat:@"%d",group.unReadCount] forState:UIControlStateNormal];
        }
        self.unreadButton.hidden = NO;
    } else {
        [self.unreadButton setTitle:@" " forState:UIControlStateNormal];
        self.unreadButton.hidden = YES;
    }
    self.todoStatus.backgroundColor = [UIColor clearColor]; // 恢复默认
    
    if (group.busy || GlobalBusy) {
        self.busyImageView.hidden = NO;
    } else {
        self.busyImageView.hidden = YES;
    }
    
    switch (group.gType.intValue) {
        case ICGroup_DOUBLE:
        {
            
            if ([ICSyncManager sharedInstance].isSynchronizing) {
                _avatarImageView.imageView.image = [UIImage imageNamedFromiComeSDKBundle:@"App_personal_headimg"];
                return;
            }
            
            __block NSURL *url;
            __block ICUser * wUser;
            [ICMessageDatabase getUsersWithGroupId:group.gId finish:^(NSArray *array, NSError *error) {
                for (ICUser *gUser in array) {
                    if (![gUser.eId isEqualToString:[ICUser currentUser].eId]){
                        wUser = gUser;
                        NSString *photoId = gUser.photoId;
                        if ([ICTools stringEmpty:photoId]) {
                            photoId = group.photoId;
                            wUser.photoId = group.photoId;
                        }
                        url = [NSURL URLWithString:[ICTools getMinImageURL:(photoId)]];
                    }
                }
            }];
            
            NSString *URL = [ICTools getMinImageURL:(wUser.photoId)];
            [UIImage addAvatariamgeView:_avatarImageView.imageView withUrlStr:URL witheId:wUser.eId withName:wUser.eName ];
            
            break;
        }
         case ICGroup_MULTI:
        {
            NSString *URL = [ICTools getOglImageURL:(group.photoId)];
            [UIImage GroupHeadView:_avatarImageView.imageView withUrlStr:URL withgId:group.gId withSize:CGSizeMake(200,200)];
            
            break;
        }
        case ICGroup_SELF:
        {
            NSString *URL = [ICTools getMinImageURL:([ICUser currentUser].photoId)];
           [UIImage addAvatariamgeView:_avatarImageView.imageView withUrlStr:URL witheId:[ICUser currentUser].eId withName:[ICUser currentUser].eName];
            break;
        }
        case ICGroup_CHANCE:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_chance"] options:SDWebImageRetryFailed];
            break;
        }
        case ICGroup_GENIUS:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"App_group_headimg"] options:SDWebImageRetryFailed];
            break;
        }
        case ICGroup_NOTIFY:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_notify"] options:SDWebImageRetryFailed];
            break;
        }
        case ICGroup_TODO:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_todo"] options:SDWebImageRetryFailed];
            
            [ICMessageDatabase selectAllMessage:group.gId finish:^(NSArray *array, NSError *error) {
                self.unreadButton.hidden = YES;
                for (ICMessageFrame *messageFrame in array) {
                    if (messageFrame.model.message.status == ICMessageStatus_unRead && ![ICTools stringEmpty:messageFrame.model.message.messageId]) {
                        self.todoStatus.backgroundColor = [UIColor redColor];
                        self.unreadButton.hidden = YES;
                        break;
                    }
                }
            }];
            break;
        }
        case ICGroup_ROBOT:
        {
            __block NSURL *url;
            if ([ICMessageHelper isServeRbtGroup:group.gId gType:[NSString stringWithFormat:@"%d", ICGroup_ROBOT]]) {
                [ICMessageDatabase getUsersWithGroupId:group.gId finish:^(NSArray *array, NSError *error) {
                    for (ICUser *gUser in array) {
                        if (![gUser.eId isEqualToString:[ICUser currentUser].eId]){
                            url = [NSURL URLWithString:[ICTools getMinImageURL:(gUser.photoId)]];
                        }
                    }
                }];
            }
            NSString *placeholderImage = @"icon_message_spirit";
            if ([ICMessageHelper isUserRbtGroup:group.gId gType:group.gType]) {
                placeholderImage = @"icon_message_spirit";
            } else {
                placeholderImage = @"App_personal_headimg";
            }
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:placeholderImage] options:SDWebImageRetryFailed];
            break;
        }
        case ICGroup_SERVICE:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_spirit_service"] options:SDWebImageRetryFailed];
            break;
        }
            case ICGroup_DIRECTM:
        {
            NSURL *url = [NSURL URLWithString:[ICTools getMinImageURL:(group.photoId)]];
            [_avatarImageView.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_notice"] options:SDWebImageRetryFailed];
            break;
        }
        default:
            break;
    }
    if (self.isSearch) { // 搜索处理
         [_usernameLabel setAttributedText:[NSMutableAttributedString searchTtitle:group.gName key:self.keyString keyColor:SEARCH_HEIGHT_COLOR]];
    } else {
        [_usernameLabel setText:group.gName];
    }
    
    if (group.unReadCount != 0 && group.status == 1) { // @与草稿优先级逻辑处理
        _alertMessageLabel.text = @"[有人@我]";
        [_messageLabel setText:group.lastMsgString];
    } else {
        _alertMessageLabel.text = @"";
        if (!group.isDraft) {
            [_messageLabel setText:group.lastMsgString];
        } else {
            [_messageLabel setAttributedText:[self drfitString:group.lastMsgString]];
        }
    }
    
    if (group.lastMsgTime == 0) {
        [_dateLabel setText:@" "];
    } else {
        [_dateLabel setText:[ICMessageHelper timeFormatWithDate3:group.lastMsgTime]];
    }
}

- (void)setSearchMessage:(ICSearchMessage *)searchMessage
{
    _searchMessage = searchMessage;
    NSString *URL = [ICTools getMinImageURL:(searchMessage.photoId)];
    [UIImage addAvatariamgeView:_avatarImageView.imageView withUrlStr:URL witheId:searchMessage.eId withName:searchMessage.eName];

    [_usernameLabel setText:searchMessage.eName];
    [_messageLabel setAttributedText:[NSMutableAttributedString searchTtitle:searchMessage.messageTxt key:searchMessage.key keyColor:SEARCH_HEIGHT_COLOR]];
    [_dateLabel setText:
     [ICMessageHelper timeFormatWithDate3:searchMessage.date]];
    self.unreadButton.hidden = YES;
}

- (NSMutableAttributedString *)drfitString:(NSString *)draft
{
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"[草稿] " attributes:@{
                                                                                                                   NSFontAttributeName:[UIFont systemFontOfSize:14],                                                                  NSForegroundColorAttributeName:ICRGB(0xd34949)                                                                   }];
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:draft attributes:@{
                                                                                                          NSFontAttributeName:[UIFont systemFontOfSize:14],                                                        NSForegroundColorAttributeName:ICRGB(0x9a9a9a)
                                                                                                          }];
    [attString appendAttributedString:str];
    return attString;
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat imageWidth = 50 * App_Frame_Width / 375.0f;
    self.leftFreeSpace = leftPadding * App_Frame_Width / 375.0f;
    [self.avatarImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(imageWidth,imageWidth));
        make.centerY.equalTo(self.contentView.mas_centerY);
        make.left.equalTo(self.contentView.mas_left).offset(10);
    }];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.equalTo(self.mas_top).offset(14);
        make.width.mas_equalTo(70);
    }];
    
    [_usernameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(13);
        make.left.equalTo(self.avatarImageView.mas_right).offset(10);
        make.right.equalTo(self.dateLabel.mas_left).offset(-5);
    }];

    [self.todoStatus mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.avatarImageView.mas_right).offset(-1);
        make.centerY.equalTo(self.avatarImageView.mas_top).offset(1);
        make.size.mas_equalTo(CGSizeMake(10, 10));
    }];

    [self.alertMessageLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_usernameLabel.mas_left);
        make.bottom.equalTo(self.avatarImageView.mas_bottom).offset(-5);
    }];

    [_messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.alertMessageLabel.mas_right);
        make.right.equalTo(_dateLabel.mas_left).offset(-10);
        make.bottom.equalTo(self.avatarImageView.mas_bottom).offset(-5);
    }];

    [_unreadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.avatarImageView.mas_right).offset(-1);
        make.centerY.equalTo(self.avatarImageView.mas_top).offset(2);
    }];

    [self.busyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView.mas_right).offset(-10);
        make.centerY.equalTo(self.messageLabel.mas_centerY);
    }];
}


#pragma mark - Getter and Setter

- (UIView *) avatarImageView
{
    if (_avatarImageView == nil) {
        ICHeadImageView *imageV = [[ICHeadImageView alloc] init];
        [self.contentView addSubview:imageV];
        _avatarImageView = imageV;
    }
    return _avatarImageView;
}

- (UILabel *) usernameLabel
{
    if (_usernameLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        _usernameLabel.textColor = ICRGB(0x222222);
        [self.contentView addSubview:label];
        _usernameLabel = label;
    }
    return _usernameLabel;
}

- (UILabel *) dateLabel
{
    if (_dateLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        [label setTextAlignment:NSTextAlignmentRight];
        [label setTextColor:ICRGB(0xc9c9c9)];
        [self.contentView addSubview:label];
        _dateLabel = label;
    }
    return _dateLabel;
}

- (UILabel *) messageLabel
{
    if (_messageLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        [label setTextColor:ICRGB(0x969696)];
        [self.contentView addSubview:label];
        _messageLabel = label;
    }
    return _messageLabel;
}

- (UILabel *)alertMessageLabel {
    if (!_alertMessageLabel) {
        _alertMessageLabel = [[UILabel alloc] init];
        _alertMessageLabel.textColor = ICRGB(0xd34949);
        [self.contentView addSubview:_alertMessageLabel];
    }
    return _alertMessageLabel;
}

- (UIButton *)unreadButton
{
    if (!_unreadButton) {
        _unreadButton = [[UIButton alloc] init];
        [self.contentView addSubview:_unreadButton];
        _unreadButton.layer.masksToBounds = YES;
        _unreadButton.layer.cornerRadius = 8;
        _unreadButton.contentEdgeInsets   = UIEdgeInsetsMake(1, 5, 1, 5);
//        _unreadButton.backgroundColor = [UIColor redColor];
        _unreadButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_unreadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_unreadButton setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
//        [_unreadButton setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
        
    }
    return _unreadButton;
}

-(UILabel *)todoStatus {
    if (!_todoStatus) {
        _todoStatus = [[UILabel alloc] init];
        _todoStatus.layer.masksToBounds = YES;
        _todoStatus.layer.cornerRadius = 5;
        [self.contentView addSubview:_todoStatus];
    }
    return _todoStatus;
}


-(UIImageView *)busyImageView {
    if (!_busyImageView) {
        _busyImageView = [[UIImageView alloc] init];
        _busyImageView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_message_busy"];
        _busyImageView.hidden = YES;
        [self.contentView addSubview:_busyImageView];
    }
    return _busyImageView;
}


@end
